package test.ground.cotroller;

import com.wang.tool.common.result.SimpleResult;
import com.wang.tool.compile.JdkDynamicCompiler;
import com.wang.tool.monitor.InvokeTemplate;
import com.wang.tool.monitor.LinkLogUtil;
import com.wang.tool.monitor.core.MonitorInfo;
import com.wang.tool.monitor.template.AbsMonitorInvoker;
import com.wang.tool.okhttp.HttpTemplate;
import okhttp3.*;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import test.ground.model.KS;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @Author wangshaopeng
 * @Date 2020/12/28
 */
@Controller
@RequestMapping("/common")
public class CommonController {

    private List<Object> objs = new ArrayList<>();

//    @PostConstruct
//    public void init() {
//
//        List<FlowRule> flowRules = new ArrayList<>();
//
//        //创建流控规则对象
//        FlowRule flowRule = new FlowRule();
//        //设置流控规则 QPS
//        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
//        //设置受保护的资源
//        flowRule.setResource("HelloSentinel");
//        //设置受保护的资源的阈值
//        flowRule.setCount(1);
//
//
//        flowRules.add(flowRule);
//
//        //加载配置好的规则
//        FlowRuleManager.loadRules(flowRules);
//    }

//    @Transactional
//    @Cacheable(value = "hsetmealCache",key = "#h")
    @RequestMapping("/h")
    public String helloWorld(String h) throws InterruptedException {

//        Thread.sleep(60000);
        JdkDynamicCompiler compiler = new JdkDynamicCompiler();
//        objs.add(compiler.compile(h));
        InvokeTemplate.monitor("t1", "t2", new AbsMonitorInvoker<Object>(h) {
            @Override
            public Object internalCall() throws Throwable {
                if(true){
                    throw new RuntimeException(new IllegalArgumentException("111"));
                }
                return null;
            }

            @Override
            protected void internalAfter(MonitorInfo<Object> monitorInfo) throws Throwable {
                LinkLogUtil.info("1113,{0}",monitorInfo.getError().getStacks());
            }
        });

        return h ;
    }

    @RequestMapping("/j")
    public SimpleResult<String> j(String j2){
        if("j".equals(j2)){
            throw new IllegalArgumentException("j");
        }
        return SimpleResult.success(get(j2));
    }

    private String get(String s){
        JdkDynamicCompiler compiler = new JdkDynamicCompiler();
        objs.add(compiler.compile(s));
        return s ;
    }


    @RequestMapping("/b")
//    @WrapResponse(ops = "车接车送1")
    public HashMap b(@org.springframework.web.bind.annotation.RequestBody HashMap<Integer, KS> body){
        return body;
    }

    @RequestMapping("/d")
    public KS d(Integer id,@org.springframework.web.bind.annotation.RequestBody KS ks ){
        System.out.println(id);
        return ks;
    }


    @RequestMapping("/d2")
    public int d2(Integer id,Collection<String> ids){
        System.out.println(id);
        return -1;
    }


    @PostMapping("/sse")
    public SseEmitter handleSse(HttpTemplate httpTemplate) {
        SseEmitter emitter = new SseEmitter();
//        HttpTemplate.sse("https://idealab.alibaba-inc.com/aigc/v1/askTextToTextMsg", 300000, new SseHandler<Object>() {
//            @Override
//            public void fillRequest(Request.Builder builder) {
////                添加请求头
//                builder.addHeader("X-AK", "960e8043748ecf032cc4936ba1446c1e");
//                okhttp3.RequestBody reqbody = okhttp3.RequestBody.create("{ \"model\": \"gpt-4 8K\",  \"prompt\": \"你好\", \"stream\": true, \"contentType\": \"text\", \"curiosity\": \"lv4\", \"maxTokens\": 200 }", MediaType.parse("application/json; charset=utf-8"));
//                builder.post(reqbody);
//
//
//                LinkLogUtil.info("开启");
//            }
//
//            @Override
//            public void onReadLine(String line) {
//                LinkLogUtil.info("读到数据:"+line);
//                try {
//                    emitter.send(SseEmitter.event().name("message").data(line));
//                } catch (IOException e) {
//                    throw new RuntimeException(e);
//                }
//
//            }
//
//            @Override
//            public Object onFinished() {
//                LinkLogUtil.info("结束了:");
//                // 发送完所有事件后完成请求
//                emitter.complete();
//                return null;
//            }
//
//            @Override
//            public Object onError(Throwable error) throws Throwable {
//                LinkLogUtil.info("异常了:"+error);
//                emitter.completeWithError(error);
//                return null;
//            }
//        });



        // 异步处理，防止阻塞
        CompletableFuture.runAsync(() -> {
            try {
                // 对事件进行转发
                for (int i = 0; i < 10; i++) {
                    Thread.sleep(1000);
                    emitter.send(SseEmitter.event().name("message").data(i));
                }
                // 发送完所有事件后完成请求
                emitter.complete();
            } catch (Exception ex) {
                emitter.completeWithError(ex);
            }
        });
        return emitter;
    }

//
//    @PostMapping("/dis")
//    public SseEmitter disStreamForward(HttpServletRequest servletRequest) throws IOException {
////        String url = "https://idealab.alibaba-inc.com/aigc/v1/askTextToTextMsg";
//        String url = "http://localhost:70/common/sse";
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(org.springframework.http.MediaType.parseMediaType(servletRequest.getContentType()));
//        // Copy other headers if needed
//        Enumeration<String> headerNames = servletRequest.getHeaderNames();
//        while (headerNames.hasMoreElements()) {
//            String headerName = headerNames.nextElement();
//            headers.set(headerName, servletRequest.getHeader(headerName));
//        }
//        String requestBody = new BufferedReader(new InputStreamReader(servletRequest.getInputStream()))
//                .lines().collect(Collectors.joining("\n"));
//
//        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);
//        AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate();
//        SseEmitter emitter = new SseEmitter();
//
//        ListenableFuture<ResponseEntity<String>> future = asyncRestTemplate.exchange(url, HttpMethod.POST, entity, String.class);
//
//        future.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
//            @Override
//            public void onSuccess(ResponseEntity<String> result) {
//                try {
//                    String[] events = result.getBody().split("\n");
//                    for (String event : events) {
//                        System.out.println("转发,"+event);
//                        emitter.send(event, org.springframework.http.MediaType.TEXT_PLAIN);
//                    }
//                    emitter.complete();
//                } catch (IOException e) {
//                    emitter.completeWithError(e);
//                }
//            }
//
//            @Override
//            public void onFailure(Throwable ex) {
//                emitter.completeWithError(ex);
//            }
//        });
//
//        return emitter;
//    }
private RestTemplate restTemplate = new RestTemplate();

    /**
     * 同步转发
     * @param request
     * @param response
     */
//    @RequestMapping(value = "/sync_forward", method = {RequestMethod.POST})
    @PostMapping("/sync_forward")
    public void syncForward(HttpServletRequest request,String key,String vip, HttpServletResponse response,@org.springframework.web.bind.annotation.RequestBody byte[] requestBody) {
        try {
            System.out.println(vip);
            String url = "https://idealab.alibaba-inc.com/aigc/v1/askTextToTextMsg";
//            Map<String,String> headers1 = new HashMap<>();
//            for (String headerName : Collections.list(request.getHeaderNames())) {
//                headers1.put(headerName, request.getHeader(headerName));
//            }
//            String body = HttpTemplate.jsonPost(url,300000,headers1,new String(requestBody));
//            System.out.println(body);

            HttpHeaders headers = new HttpHeaders();
//            Collections.list(request.getHeaderNames())
            for (String headerName : Arrays.asList("X-AK","Content-Type")) {
                headers.add(headerName, request.getHeader(headerName));
            }

            // Create a new HttpEntity with headers and request body
            HttpEntity<byte[]> httpEntity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<byte[]> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, byte[].class);
//            HttpHeaders responseHeaders = responseEntity.getHeaders();
//             -> {LinkedList@11128}  size = 1
//             -> {LinkedList@11104}  size = 1
//             -> {LinkedList@11118}  size = 1
//             -> {LinkedList@11106}  size = 1
//            Connection -> {LinkedList@11108}  size = 1
//            for (String headerName : responseHeaders.keySet()) {
//                String first = responseHeaders.getFirst(headerName);
//                if (first==null) {
//                    continue;
//                }
//                response.addHeader(headerName, first);
//            }
//            response.setCharacterEncoding("UTF-8");
            response.addHeader("Content-Type",responseEntity.getHeaders().getFirst("Content-Type"));
            response.getOutputStream().write(responseEntity.getBody());
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            LinkLogUtil.error("sync_forward_error", e, "转发失败,{0}", e.getMessage());
        }
    }


    /**
     * sse转发
     * @param servletRequest
     * @param requestBody
     * @param servletResponse
     * @return
     */
    @PostMapping("/sse_forward")
    public SseEmitter sseForward(HttpServletRequest servletRequest, @org.springframework.web.bind.annotation.RequestBody byte[] requestBody,
                                 HttpServletResponse servletResponse) {
        //sse不支持写header，这里可以返回前写个固定的头
//        servletResponse.setHeader("Your-Header-Name", "Your-Header-Value");
        SseEmitter emitter = new SseEmitter();
        try {
            String url = "https://idealab.alibaba-inc.com/aigc/v1/askTextToTextMsg";
            OkHttpClient client = new OkHttpClient();
            okhttp3.MediaType mediaType = okhttp3.MediaType.parse(servletRequest.getContentType());
            okhttp3.RequestBody reqbody = okhttp3.RequestBody.create(requestBody, mediaType);
            okhttp3.Request.Builder reqBuilder = new Request.Builder().url(url).post(reqbody);
            Enumeration<String> headerNames = servletRequest.getHeaderNames();
//            while (headerNames.hasMoreElements()) {
//                String headerName = headerNames.nextElement();
//                reqBuilder.addHeader(headerName, servletRequest.getHeader(headerName));
//            }
            reqBuilder.addHeader("X-AK", servletRequest.getHeader("X-AK"));

            Request request = reqBuilder.build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    emitter.completeWithError(e);
                }
                @Override
                public void onResponse(Call call, Response response) {
                    try (BufferedReader reader = new BufferedReader(response.body().charStream())) {
                        String line;
                        while ((line = reader.readLine()) != null) {
                            emitter.send(line, org.springframework.http.MediaType.TEXT_PLAIN);
                        }
                        emitter.complete();
                    } catch (Exception e) {
                        emitter.completeWithError(e);
                    }
                }
            });
        } catch (Exception e) {
            emitter.completeWithError(e);
        }
        return emitter;
    }



    public static void main(String[] args) throws ExecutionException, InterruptedException {
        HashMap<String, String> headers = new HashMap<>();
        headers.put("X-AK", "960e8043748ecf032cc4936ba1446c1e");
        String url = "http://localhost:70/common/sync_forward";
//        url = "http://localhost:70/common/sse_forward";
//        url = "https://idealab.alibaba-inc.com/aigc/v1/askTextToTextMsg";
        String xx = HttpTemplate.jsonPost(url, 60000, headers, "{ \"model\": \"gpt-3.5-turbo\",  \"prompt\": \"\", \"stream\": false, \"contentType\": \"text\", \"curiosity\": \"lv4\", \"maxTokens\": 200 }");
        System.out.println(xx);
        //        url = "http://localhost:70/common/sse_forward";
        url = "https://idealab.alibaba-inc.com/aigc/v1/askTextToTextMsg";
        xx = HttpTemplate.jsonPost(url, 60000, headers, "{ \"model\": \"gpt-3.5-turbo\",  \"prompt\": \"\", \"stream\": false, \"contentType\": \"text\", \"curiosity\": \"lv4\", \"maxTokens\": 200 }");
        System.out.println(xx);




//        String url = "https://idealab.alibaba-inc.com/aigc/v1/askTextToTextMsg";
////        url = "http://localhost:70/common/sse_forward";
//        HttpTemplate.sse(url, 30000, new SseHandler<Void>() {
//            @Override
//            public void fillRequest(Request.Builder builder) {
////                builder.post("{}");
////                okhttp3.
//                okhttp3.RequestBody reqbody = okhttp3.RequestBody.create("{ \"model\": \"gpt-3.5-turbo\",  \"prompt\": \"春天为题写200字作文\", \"stream\": true, \"contentType\": \"text\", \"curiosity\": \"lv4\", \"maxTokens\": 500 }", MediaType.parse("application/json; charset=utf-8"));
//                builder.addHeader("X-AK", "960e8043748ecf032cc4936ba1446c1e");
//
//
//                builder.post(reqbody);
//
//
//
//            }
//
//            @Override
//            public void onReadLine(String line) {
//                System.out.println("收到"+line);
//            }
//
//            @Override
//            public Void onFinished() {
//                System.out.println("结束了");
//
//                return null;
//            }
//
//            @Override
//            public Void onError(Throwable error) throws Throwable {
//                return null;
//            }
//        }).get();
    }




}
